/**
 * a+ 方式打开文件 & 读 & 追加: https://www.bilibili.com/video/BV1vs411n7TH/?p=124
 */
#include <stdio.h>
#include "../Utils/FileIOUtils.h"

static char *FILE_READ_PATH = "../Read_Write_Test/test.txt";
static char *FILE_RAND_WRITE_PATH = "../Read_Write_Test/9.5.'a+'方式读&追加文件.txt";

void copy();
void appent();

int main() {
    //1.先copy一份
    copy();
    //2.追加
    appent();

    return EXIT_SUCCESS;
}

//1.先拷贝一份, 从拷贝文件里随机写
void copy() {
    int fail0 = file_copy(FILE_READ_PATH, FILE_RAND_WRITE_PATH, 1);
    if (fail0) {
        printf("拷贝失败, fail = %d\n", fail0);
    } else {
        printf("拷贝成功!\n");
    }
}

//2.追加方式打开文件
void appent() {
    FILE *write = file_open_a_plus(FILE_RAND_WRITE_PATH);
    long pos0 = file_tell(write);
    printf("光标当前位置: pos0 = %ld\n", pos0);   //0

    //在尾部追加
    int fail1 = file_puts("//1.你好呀, 11111111!\n", write);
    if (fail1) {
        printf("直接在末尾追加失败: fail1 = %d\n", fail1);
    } else {
        printf("直接在末尾追加成功!\n");
    }

    //从尾部移动光标
    int fail2 = file_seek(write, -382, SEEK_END);
    printf("1.光标从SEEK_END(末尾位置)偏移 %d 位\n", -382);
    long pos1 = file_tell(write);
    printf("光标当前位置: pos1 = %ld\n", pos1);   //690

    //读一行
    char arr[100] = {0};
    char *str0 = file_gets(arr, 100, write);
    printf("读取1行: \"%s\"\n", arr);
    long pos2 = file_tell(write);
    printf("读一行后, 光标当前位置: pos2 = %ld\n", pos2);   //799

    //读取后, 调用fseek()随便传个值, 否则不能再追加
    file_seek(write, 0, SEEK_CUR);
    long pos3 = file_tell(write);
    printf("读取后, 调用fseek(0)随便传个值, 否则不能再追加. 光标当前位置: pos3 = %ld\n", pos3);//799

    //再在末尾追加
    int fail3 = file_puts("//2.你好呀, 222222222!\n", write);
    if (fail3) {
        printf("再在末尾追加失败: fail3 = %d", fail3);
    } else {
        printf("再在末尾追加成功!\n");
    }
    file_close(write);
}